//
//  RCMerchantDetailWriteCommentViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-9-20.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCMerchantDetailWriteCommentViewController.h"
#import "CommonDefines.h"
#import "UIColor-Expanded.h"
#import "NSArray+EX.h"
#import "GloableEngineService.h"
#import "AppDelegate.h"
#import "FrameworkRelativeDefines.h"
#import "RCFeedbackDataModel.h"
#import "NSString+NSString_Ex_.h"

#define kLeftButtonImageFile         @"image_merchantDetail_write_leftButton.png"
#define kRightButtonImageFile             @"image_merchantDetail_write_rightButton.png"
#define kStarActiveimageFile      @"image_merchantDetail_write_star_active.png"
#define kStarInActiveimageFile      @"image_merchantDetail_write_star_inactive.png"
#define kFormImageFile           @"image_merchant_commit_form.png"
#define kTextViewHolderStr       @"输入评价，人人为我，我为人人"

@interface RCMerchantDetailWriteCommentViewController ()

@property(nonatomic,retain)UIButton *leftButton;
@property(nonatomic,retain)UIButton *rightButton;
@property(nonatomic,copy)NSString *merchantID;
@property(nonatomic,copy)NSString *merchantName;
@property(nonatomic,retain)UIButton *startImageView1;
@property(nonatomic,retain)UIButton *startImageView2;
@property(nonatomic,retain)UIButton *startImageView3;
@property(nonatomic,retain)UIButton *startImageView4;
@property(nonatomic,retain)UIButton *startImageView5;
@property(nonatomic,retain)UITextView *contentTextView;
@property(nonatomic,retain)UITextField *contentTextField;
@property(nonatomic,assign)NSInteger currentLastNumber;
@property(nonatomic,retain)UILabel  *wordCountLabel;
@property(nonatomic,retain)NSMutableArray *starArray;
@property(nonatomic,retain)MBProgressHUDEx *progressHub;
@property(nonatomic,assign)int64_t requestID;
@property(nonatomic,assign)NSInteger score;


@end

@implementation RCMerchantDetailWriteCommentViewController

@synthesize leftButton = _leftButton;
@synthesize rightButton = _rightButton;
@synthesize merchantID = _merchantID;
@synthesize merchantName = _merchantName;
@synthesize startImageView1 = _startImageView1;
@synthesize startImageView2 = _startImageView2;
@synthesize startImageView3 = _startImageView3;
@synthesize startImageView4 = _startImageView4;
@synthesize startImageView5 = _startImageView5;
@synthesize contentTextView = _contentTextView;
@synthesize contentTextField = _contentTextField;
@synthesize currentLastNumber = _currentLastNumber;
@synthesize wordCountLabel = _wordCountLabel;
@synthesize starArray = _starArray;
@synthesize progressHub = _progressHub;
@synthesize requestID = _requestID;
@synthesize score = _score;
@synthesize delegate = _delegate;

@synthesize isFromPointsShop = _isFromPointsShop;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)dealloc{
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
    _requestID = kInvalidRequestId;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    self.delegate = nil;
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.leftButton = nil;
    self.rightButton = nil;
    self.merchantName = nil;
    self.merchantID = nil;
    self.starArray = nil;
    self.startImageView1 = nil;
    self.startImageView2 = nil;
    self.startImageView3 = nil;
    self.startImageView4 = nil;
    self.startImageView5 = nil;
    self.contentTextView = nil;
    self.contentTextField = nil;
    self.wordCountLabel = nil;
    [super dealloc];
}

-(id)initWithMerchant:(NSString *)merchantID withName:(NSString *)merchantName{
    self = [super init];
    if (self) {
        self.merchantID = merchantID;
        self.merchantName = merchantName;
        _starArray = [[NSMutableArray alloc]initWithCapacity:5];
        self.score = 0;
        [self initKeyBoard];
    }
    return self;
}

-(void)initKeyBoard{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)loadView{
    [super loadView];
    _leftButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [_leftButton setImage:[UIImage imageNamed:kLeftButtonImageFile]
                 forState:UIControlStateNormal];
    [_leftButton setImage:[UIImage imageNamed:kLeftButtonImageFile]
                 forState:UIControlStateHighlighted];
    [_leftButton addTarget:self action:@selector(leftButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [self createLeftBarButtonItemWithButton:_leftButton];
    
    _rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >=7.0) {
        _rightButton.frame = CGRectMake(10, 0, 44, 44);
    }
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                  forState:UIControlStateNormal];
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                  forState:UIControlStateHighlighted];
    [_rightButton addTarget:self action:@selector(rightButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [self createLeftBarButtonItemWithButton:_rightButton];
    
    self.navigationItem.titleView = [self createTwolineTitleView];
}

-(UIView *)createTwolineTitleView{
    UIView *titleView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 150, 44)]autorelease];
    UILabel *upperLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 150, 15)];
    upperLabel.backgroundColor = [UIColor clearColor];
    upperLabel.textColor = [UIColor whiteColor];
    upperLabel.textAlignment = UITextAlignmentCenter;
    upperLabel.font = [UIFont fontWithName:kFontNameHeiti size:15];
    upperLabel.shadowColor = [UIColor colorWithHex:0xff2c2c2];
    upperLabel.shadowOffset = CGSizeMake(0, 0.5);
    upperLabel.text = @"添加点评";
    [titleView addSubview:upperLabel];
    [upperLabel release];
    
    UILabel *downLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 24, 150, 15)];
    downLabel.backgroundColor = [UIColor clearColor];
    downLabel.textColor = [UIColor whiteColor];
    downLabel.textAlignment = UITextAlignmentCenter;
    downLabel.font = [UIFont fontWithName:kFontNameHeiti size:15];
    downLabel.shadowColor = [UIColor colorWithHex:0xff2c2c2];
    downLabel.shadowOffset = CGSizeMake(0, 0.5);
    downLabel.text = self.merchantName;
    [titleView addSubview:downLabel];
    [downLabel release];
    return titleView;
}

-(void)leftButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    _startImageView1 = [[UIButton alloc]initWithFrame:CGRectMake(82, 13, 28, 27)];
    _startImageView1.backgroundColor = [UIColor clearColor];
    _startImageView1.tag = 101;
    [_startImageView1 setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarInActiveimageFile ofType:nil]] forState:UIControlStateNormal];
    [_startImageView1 addTarget:self action:@selector(starButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_starArray addObject:_startImageView1];
    [self.viewContainer addSubview:_startImageView1];
    
    _startImageView2 = [[UIButton alloc]initWithFrame:CGRectMake(114, 13, 28, 27)];
    _startImageView2.backgroundColor = [UIColor clearColor];
    _startImageView2.tag = 102;
    [_startImageView2 setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarInActiveimageFile ofType:nil]] forState:UIControlStateNormal];
    [_startImageView2 addTarget:self action:@selector(starButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_starArray addObject:_startImageView2];
    [self.viewContainer addSubview:_startImageView2];
    
    _startImageView3 = [[UIButton alloc]initWithFrame:CGRectMake(146, 13, 28, 27)];
    _startImageView3.backgroundColor = [UIColor clearColor];
    _startImageView3.tag = 103;
    [_startImageView3 setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarInActiveimageFile ofType:nil]] forState:UIControlStateNormal];
    [_startImageView3 addTarget:self action:@selector(starButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_starArray addObject:_startImageView3];
    [self.viewContainer addSubview:_startImageView3];
    
    _startImageView4 = [[UIButton alloc]initWithFrame:CGRectMake(178, 13, 28, 27)];
    _startImageView4.backgroundColor = [UIColor clearColor];
    _startImageView4.tag = 104;
    [_startImageView4 setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarInActiveimageFile ofType:nil]] forState:UIControlStateNormal];
    [_startImageView4 addTarget:self action:@selector(starButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_starArray addObject:_startImageView4];
    [self.viewContainer addSubview:_startImageView4];
    
    _startImageView5 = [[UIButton alloc]initWithFrame:CGRectMake(210, 13, 28, 27)];
    _startImageView5.backgroundColor = [UIColor clearColor];
    _startImageView5.tag = 105;
    [_startImageView5 setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarInActiveimageFile ofType:nil]] forState:UIControlStateNormal];
    [_startImageView5 addTarget:self action:@selector(starButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_starArray addObject:_startImageView5];
    [self.viewContainer addSubview:_startImageView5];
    
    UIImageView *textImageView = [[UIImageView alloc]initWithFrame:CGRectMake(16, 55, 288, 111)];
    textImageView.backgroundColor = [UIColor clearColor];
    UIImage *textImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kFormImageFile ofType:nil]];
    textImage = [textImage resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
    [textImageView setImage:textImage];
    textImageView.userInteractionEnabled = YES;
    
    _contentTextView = [[UITextView alloc]initWithFrame:textImageView.bounds];
    _contentTextView.backgroundColor = [UIColor clearColor];
    _contentTextView.delegate = self;
    _contentTextView.textColor = [UIColor colorWithHex:0xff989797];
    _contentTextView.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    [_contentTextView setReturnKeyType:UIReturnKeyDone];
    _contentTextView.text = kTextViewHolderStr;
    
    [textImageView addSubview:_contentTextView];
    
    _wordCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(228,88,50,13)];
    _wordCountLabel.backgroundColor = [UIColor clearColor];
    _wordCountLabel.textColor = [UIColor colorWithHex:0xff989797];
    _wordCountLabel.font = [UIFont fontWithName:kFontNameHelvetica size:12];
    _wordCountLabel.textAlignment = UITextAlignmentRight;
    _wordCountLabel.text = @"140";
    [textImageView addSubview:_wordCountLabel];
    
    
    [self.viewContainer addSubview:textImageView];
    [textImageView release];
    
    
    //积分商城的点评不需要人均
    if (!self.isFromPointsShop) {
        
        UIImageView *textFiledImageView = [[UIImageView alloc]initWithFrame:CGRectMake(16, 180, 288, 31)];
        textFiledImageView.backgroundColor = [UIColor clearColor];
        textFiledImageView.userInteractionEnabled = YES;
        UIImage *textFiledImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kFormImageFile ofType:nil]];
        textFiledImage = [textFiledImage resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
        [textFiledImageView setImage:textFiledImage];
        
        UILabel *emailLabel = [[UILabel alloc]initWithFrame:CGRectMake(3, 7, 100, 16)];
        emailLabel.backgroundColor = [UIColor clearColor];
        emailLabel.textColor = [UIColor colorWithHex:0xff505050];
        emailLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
        emailLabel.text = @"人均（选填）";
        [textFiledImageView addSubview:emailLabel];
        [emailLabel release];
        
        _contentTextField = [[UITextField alloc]initWithFrame:CGRectMake(115, 9, 160, 13)];
        _contentTextField.backgroundColor = [UIColor clearColor];
        _contentTextField.delegate = self;
        _contentTextField.textColor = [UIColor colorWithHex:0xff989797];
        _contentTextField.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
        _contentTextField.textAlignment = UITextAlignmentRight;
        _contentTextField.placeholder = @"点击输入人均";
        [_contentTextField setReturnKeyType:UIReturnKeyDone];
        [textFiledImageView addSubview:_contentTextField];
        
        
        [self.viewContainer addSubview:textFiledImageView];
        [textFiledImageView release];
    }
    
}

#pragma mark -
#pragma mark UITextView Delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:kTextViewHolderStr]) {
        textView.textColor = [UIColor colorWithHex:0xff505050];
        textView.text=@"";
    }
    
    return YES;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.textColor = [UIColor colorWithHex:0xff989797];
        textView.text = kTextViewHolderStr;
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    int length = 0;
    length = [textView.text length];
    _currentLastNumber = 140 - length;
    _wordCountLabel.text = [NSString stringWithFormat:@"%d",_currentLastNumber];
    if (length > 140)
    {
        _wordCountLabel.textColor = [UIColor redColor];
        _rightButton.enabled = NO;
    }else{
        _wordCountLabel.textColor = [UIColor colorWithHex:0xff989797];
        _rightButton.enabled = YES;
    }
    
}

#pragma -mark UITextFeildDelegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}



-(void)starButtonClicked:(id)sender{
    UIButton *button = (UIButton *)sender;
    NSInteger tag = button.tag;
    self.score = tag - 100;
    for (int i = 0; i < tag -100; i++) {
        UIButton *button = [_starArray safeObjectAtIndex:i];
        if (button) {
            [button setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarActiveimageFile ofType:nil]] forState:UIControlStateNormal];
        }
    }
    for (int i = tag -100; i < 5; i++) {
        UIButton *button = [_starArray safeObjectAtIndex:i];
        if (button) {
            [button setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kStarInActiveimageFile ofType:nil]] forState:UIControlStateNormal];
        }
    }
}

-(void)rightButtonClicked{
    if ([GloableEngineService sharedInstance].netWorkStatus == kNotReachable) {
        [RCAppDelegate alertWithNetworkError];
        return;
    }
    if ([_contentTextView.text isEqualToString:@""] || [_contentTextView.text isEqualToString:kTextViewHolderStr]) {
        [RCAppDelegate alertWithCustomizeString:@"没有填写任何评价哦！"];
        return;
    }
    
    NSString *price = _contentTextField.text;
    if (![NSString stringIsNullOrEmpty:price]) {
        
        NSError * error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,5}$" options:0 error:&error];
        NSTextCheckingResult * result = [regex firstMatchInString:price options:0 range:NSMakeRange(0, [price length])];
        if (!result || (regex.numberOfCaptureGroups + 1) != result.numberOfRanges) {
            [RCAppDelegate alertWithCustomizeString:@"人均价格填写有误哦"];
            _rightButton.enabled = YES;
            return;
        }
    }
   
    if (self.score == 0) {
        [RCAppDelegate alertWithCustomizeString:@"您还没有评分哦"];
        _rightButton.enabled = YES;
        return;
    }
    
    _rightButton.enabled = NO;
    
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"提交中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    
    NSString *currentScore = [NSString stringWithFormat:@"%d",self.score];
    _requestID = [[IManager sharedInstance]requestWriteCommentInfo:self.merchantID withContent:_contentTextView.text withScore:currentScore withPrice:price withDelegate:self];
    
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        RCFeedbackDataModel *feedbackDataModel = (RCFeedbackDataModel *)dataModel;
        if (feedbackDataModel.errorNO == 0) {
            [RCAppDelegate alertWithCustomizeString:@"提交成功"];
            
            if (_delegate && [_delegate respondsToSelector:@selector(successWriteComment)]) {
                [_delegate successWriteComment];
            }
            
            _rightButton.enabled = NO;
            [self performSelector: @selector(leftButtonClicked) withObject: nil afterDelay: 1.5f];
        }else{
            [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
            _rightButton.enabled = YES;
        }
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
        _rightButton.enabled = YES;
    }
}

#pragma mark -
#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    
    CGFloat keyboardOriginY = UIScreenHeight-64-keyboardRect.size.height;
//    if ([[[UIDevice currentDevice]systemVersion]floatValue] >=7.0f) {
//        keyboardOriginY = keyboardRect.origin.y;
//    }
    CGFloat buttonMaxY = CGRectGetMaxY(_contentTextField.superview.frame);
    CGFloat viewcontainOriginY = self.viewContainer.frame.origin.y;
    if (buttonMaxY + viewcontainOriginY + 5 > keyboardOriginY) {
        
        [UIView animateWithDuration:0.3f animations:^{
            CGFloat heightReduce = abs(buttonMaxY + viewcontainOriginY +5 - keyboardOriginY);
            CGRect rect = self.viewContainer.frame;
            rect.origin.y -= heightReduce;
            self.viewContainer.frame = rect;
        }];
        
    }
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3f animations:^{
        self.viewContainer.frame = self.view.bounds;
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
